package com.hp.java09_springboot.controller;

import com.hp.java09_springboot.pojo.User;
import com.hp.java09_springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/users")
    public String findAll(Model model){
        List<User> users = userService.findAll();
        model.addAttribute("users",users);
//        int x = 10 / 0;
        return "user-list";
    }

    @ResponseBody
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(@RequestBody User user){
        userService.save(user);
        return "ok";
    }

    @ResponseBody
    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String updateUser(@RequestBody User user){
        userService.modify(user);
        return "ok";
    }

    @ResponseBody
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable("id") String id){
        id = id.replace("\"","");
        userService.remove(id);
        return "ok";
    }

    @GetMapping("/user/{id}")
    public String findById(@PathVariable("id") String id,Model model){
        id = id.replace("\"","");
        User user = userService.findById(id);
        model.addAttribute("user",user);
        return "user-update";
    }


}
